package com.ta.gulimall.order.config.rabbitmq.listener;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ta.gulimall.order.config.rabbitmq.MqQueueConstant;
import com.ta.gulimall.order.service.OrderService;
import com.ta.gulimall.order.service.impl.OrderServiceImpl;
import com.ta.gulimall.order.view.entity.OrderEntity;
import com.ta.gulimall.order.view.vo.LockStoreRespVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = MqQueueConstant.ORDER_CANCEL_QUEUE)
public class OrderCancelQueueConsume {
    @Autowired
    OrderService orderService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitHandler(isDefault = true)
    public void consume(Message message, Channel channel) throws IOException {
        String body = new String(message.getBody());
        LockStoreRespVo lockStoreRespVo = JSONUtil.toBean(body, LockStoreRespVo.class);

        OrderEntity orderEntity = orderService.getById(lockStoreRespVo.getOrderId());

        //订单被手动删除
        if (orderEntity == null) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        //订单未支付
        if (orderEntity.getStatus().equals(0)) {
            OrderEntity entity = OrderEntity.builder()
                    .id(orderEntity.getId())
                    .status(4)
                    .build();
            orderService.updateById(entity);
            //解锁库存
            rabbitTemplate.convertAndSend(MqQueueConstant.DEFAULT_DIRECT_EXCHANGE, MqQueueConstant.STORE_UNLOCK_QUEUE, JSONUtil.toJsonStr(lockStoreRespVo));
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
